package kosta.controller;

import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import kosta.model.member.MemberLankVO;
import kosta.model.member.MemberService;
import kosta.model.member.MemberVO;
import kosta.model.member.TestVO;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class MemberController {
	@Resource(name = "memberServiceImpl")
	private MemberService memberService;

	private static List<TestVO> exList;
	private static int QuestionNo;
	private static int testAnswer_Check;

	// 로그인
	@RequestMapping("/login.do")
	@ResponseBody
	public ModelAndView login(HttpSession session, MemberVO vo)
			throws Exception {
		System.out.println("login");
		MemberVO mvo = memberService.login(vo);
		if (mvo != null) {
			session.setAttribute("mvo", mvo);
		}
		return new ModelAndView("home");
	}

	// 로그아웃
	@RequestMapping("/logout.do")
	public String logout(HttpSession session) {
		session.invalidate();
		System.out.println("logout");
		return "index";
	}

	// 아이디 체크
	@RequestMapping("/idCheck.do")
	@ResponseBody
	public HashMap<String, String> idCheck(HttpServletRequest request)
			throws Exception {
		MemberVO vo = memberService.idCheck(request.getParameter("id_re"));
		String str = "사용가능한 아이디.";
		if (vo != null) {
			str = "중복된 아이디.";
		}
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("str", str);
		return map;
	}

	// 회원가입 페이지로 ㄱㄱ
	@RequestMapping("/registerView.do")
	public ModelAndView registerView() {
		MemberVO vo = new MemberVO(); // validation을 위한 객체 생성
		// findById_view.jsp에서 사용할 수 있도록 전달 : commandName="findByIdForm"
		System.out.println("registerView-------");
		return new ModelAndView("registerView.member", "memberVO", vo);
	}

	// 회원가입요청 처리
	@RequestMapping(value = "/register.do", method = RequestMethod.POST)
	public ModelAndView register(@Valid MemberVO memberVO, BindingResult result)
			throws Exception {
		System.out.println("register--------" + result.hasErrors());
		if (result.hasErrors()) { // client 전송 data에 문제가 있으면 error 발생
			return new ModelAndView("registerView.member"); // 전송한 입력페이지로 다시
															// 보낸다.
			// 이때 spel에 의해 error 메세지가 제공된다.
		} else {
			System.out.println("register-------- " + memberVO);
			memberService.register(memberVO);
			System.out.println("회원가입 완료");
		}
		return new ModelAndView("register_result.member");
	}

	// 업데이트 페이지 ㄱㄱ
		@RequestMapping("/updateView.do")
		public String updateView(String id){
			System.out.println(id + "---------- id");
			return "updateView.my";
		}

	// 업데이트 처리
	@RequestMapping("/update.do")
	public String update(HttpSession session, MemberVO mvo) throws Exception {
		System.out.println(mvo + "-------- update mvo Controller");
		memberService.update(mvo);
		mvo = memberService.idCheck(mvo.getId());
		session.setAttribute("mvo", mvo);
		return "detailMember.my";
	}

	// 회원탈퇴
	@RequestMapping("/leaveMember.do")
	public String leaveMember(HttpSession session, String id) throws Exception {
		System.out.println("leaveMember --------" + id);
		memberService.leaveMember(id);
		session.invalidate();
		return "home";
	}

	// TEST View 페이지 ㄱㄱ
	@RequestMapping("/testMain.do")
	public String testMain() {
		System.out.println("test page gogo!!!");
		return "testMain.test";
	}

	@RequestMapping("/startTest.do")
	public ModelAndView startTest(int grade, String id) throws Exception {
		System.out.println(grade + " -----------startTest 등급");
		exList = memberService.testList(grade, id);
		System.out.println(exList + "---------------- exList :::");
		QuestionNo = 0;
		System.out.println(QuestionNo + "---------- start QuestionNo");
		testAnswer_Check = 0;
		System.out.println(testAnswer_Check
				+ " ------------ start testAnswer_Check");
		return new ModelAndView("redirect:testQuestion.do");
	}

	@RequestMapping("/testQuestion.do")
	public ModelAndView testQuestion() {
		TestVO vo = null;
		if (QuestionNo < 10) {
			vo = exList.get(QuestionNo);
			System.out.println(vo + "----------------" + QuestionNo + "번문제");
		}
		HashMap map = new HashMap();
		map.put("vo", vo);
		map.put("exNo", QuestionNo);

		return new ModelAndView("startTest.test", "map", map);
	}

	@RequestMapping("/answerCheck.do")
	public ModelAndView answerCheck(String userAnswer) {
		System.out.println(userAnswer + " --------- userAnswer");
		if (exList.get(QuestionNo).getAnswer().equals(userAnswer)) {
			testAnswer_Check++;
		}
		if (QuestionNo < 8) {
			QuestionNo++;
			return new ModelAndView("redirect:testQuestion.do");
		}

		return new ModelAndView("test_result.test", "testAnswer_Check",
				testAnswer_Check);
	}

	@RequestMapping("/gradeUp.do")
	public ModelAndView gradeUp(HttpSession session) throws Exception {
		MemberVO mvo = (MemberVO) session.getAttribute("mvo");
		memberService.gradeUp(mvo);
		mvo = memberService.idCheck(mvo.getId());
		session.setAttribute("mvo", mvo);
		return new ModelAndView("home");
	}

	// /////////////////쎄미//////////////////////////////////////

	// 회원 관리자 페이지로가기
	@RequestMapping("/getAllMember.do")
	public ModelAndView getAllMember(String id) throws Exception {
		List<MemberVO> list = memberService.getAllMember(id);
		return new ModelAndView("memberManage.admin", "mlist", list);
	}

	// 회원검색
	@RequestMapping("/findMemberByGrade.do")
	public ModelAndView findMemberByGrade(String id, String gradeValue)
			throws Exception {
		List<MemberVO> list = null;
		if (gradeValue.equals("all")) {
			list = memberService.getAllMember(id);
		} else {
			list = memberService.findMemberByGrade(id, gradeValue);
		}

		return new ModelAndView("memberManage.admin", "mlist", list);
	}

	// 삭제하기
	@RequestMapping("/outMember.do")
	public ModelAndView outMember(String id) throws Exception {
		System.out.println(id + "----delete id ----con");
		memberService.outMember(id);
		return new ModelAndView("redirect:getAllMember.do");
	}

	// /테스트////////////////////////////////////////////////////
	// 테스트 페이지로 가기
	@RequestMapping("/getAllTest.do")
	public ModelAndView getAllTest(String question) throws Exception {
		List<TestVO> list = memberService.getAllTest(question);
		return new ModelAndView("testManage.admin", "tList", list);
	}

	// 등급별 문제검색
	@RequestMapping("/gradeByTest.do")
	public ModelAndView gradeByTest(String question, String grade)
			throws Exception {
		List<TestVO> list = null;
		if (grade.equals("all")) {
			list = memberService.getAllTest(question);
		} else {
			list = memberService.gradeByTest(grade, question);
		}
		return new ModelAndView("testManage.admin", "tList", list);
	}

	// 수정페이지로가기
	@RequestMapping("/updateTestView.do")
	public ModelAndView updateTestView(int no) throws Exception {
		// System.out.println(no+"----updateView----");
		TestVO tvo = memberService.findByTest(no);
		// System.out.println(tvo+"-----updateView tvo----");
		return new ModelAndView("updateTest.admin", "tvo", tvo);
	}

	// 수정하기
	@RequestMapping("/updateTest.do")
	public ModelAndView updateTest(TestVO tvo) throws Exception {
		// System.out.println(tvo+"----updateView----");
		memberService.updateTest(tvo);
		return new ModelAndView("redirect:getAllTest.do");
	}

	// 삭제하기
	@RequestMapping("/removeTest.do")
	public ModelAndView removeTest(int no) throws Exception {
		memberService.removeTest(no);
		return new ModelAndView("redirect:getAllTest.do");
	}

	// 문제쓰는 페이지로가기
	@RequestMapping("/insertTestView.do")
	public String insertTestView() throws Exception {
		return "insertTest.admin";
	}

	// 추가하기
	@RequestMapping("/insertTest.do")
	public ModelAndView insertTest(TestVO tvo) throws Exception {
		memberService.insertTest(tvo);
		return new ModelAndView("redirect:getAllTest.do");
	}

	// /////////////////성광//////////////////////////////////////
	@RequestMapping("/myPage.do")
	public String memberManage() {
		return "myPage.my";
	}

	@RequestMapping("/myLankView.do")
	public ModelAndView myLankView(String id) throws Exception {
		MemberVO mvo = memberService.myLankView(id);

		MemberLankVO lankVO = memberService.findByLankID(id);
		// System.out.println(lankVO + "------------- lankvo.member");
		if (lankVO == null) {
			System.out.println("랭킹 등록이 안되있음. insert 함");
			memberService.insertMyLank(mvo);
		} else {
			System.out.println(mvo + "------------- 랭킹 mvo");
			System.out.println(lankVO + "------------- 랭킹 lankVO");
			if (lankVO.getRankpoint() != (mvo.getPoint() * 3)
					+ (6 - mvo.getGrade()) * 100) {
				System.out.println("달라서 update ㄱㄱ");
				memberService.updateMyLank(mvo);
				System.out.println("랭킹등록 되어있고 grade, point 변동사항 있음");
			}
		}
		lankVO = memberService.findByLankIdCount(id);
		System.out.println(lankVO + "------------- ModelAndView전");
		return new ModelAndView("myLankView.my", "lankVO", lankVO);
	}
}
